package com.example.common;


import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePropertySource;

import java.io.IOException;

@Slf4j
public class ResourcePropertyInit implements ApplicationContextInitializer<ConfigurableApplicationContext> {

    @Override
    public void initialize(ConfigurableApplicationContext applicationContext) {

        ConfigurableEnvironment environment = applicationContext.getEnvironment();

        String[] activeProfiles = environment.getActiveProfiles();

        if (EnvUtils.isLocal(activeProfiles)) {

            try {
                ClassLoader classLoader = getClass().getClassLoader();
                PathMatchingResourcePatternResolver resourcePatternResolver = new PathMatchingResourcePatternResolver(classLoader);
                Resource[] resources = resourcePatternResolver.getResources(String.format("classpath:*-%s.*", activeProfiles[0]));

                for (Resource resource : resources) {

                    String filename = resource.getFilename();
                    ResourcePropertySource propertySource = new ResourcePropertySource(filename, resource);
                    environment.getPropertySources().addFirst(propertySource);
                }

            } catch (IOException e) {
                log.error("**********************************ResourcePropertyInit error", e);
            }
        } else {
            log.info("********************************** ResourcePropertyInit stg no run **********************************");
        }
    }
}
